package com.jnu.myfirstapplication.data;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpUtil {
    public static String sendRequestWithOkhttp(String address)
    {
        String message="";
        try{
            OkHttpClient client=new OkHttpClient();
            Request request = new Request.Builder().url(address) .build();
            Response response= client.newCall(request).execute();
            message=response.body().string();
            return message;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }
    void parseJsonWithJsonObject(Response response) throws IOException {
        String responseData=response.body().string();
        try{
            JSONArray jsonArray=new JSONArray(responseData);
            for(int i=0;i<jsonArray.length();i++)
            {
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                String id=jsonObject.getString("id");
                String name=jsonObject.getString("name");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public String getHtmlContent(String Url){
        String content="";
        try{
            URL url = new URL(Url);
            HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
            if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
            {
                Log.d("TAG", "---into-----urlConnection---success--");

                InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(), "utf-8");
                int i;
//                String content = "";
                while((i = isr.read()) != -1)
                {
                    content = content + (char)i;
                }

                isr.close();
                httpConn.disconnect();
            }else
            {
                Log.d("TAG", "---into-----urlConnection---fail--");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return content;
    }
}
